package com.ruoyi.web.controller.inventory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.system.domain.InvInventoryTransfer;
import com.ruoyi.system.domain.InvInventoryTransferDetail;
import com.ruoyi.system.domain.Warehouse;
import com.ruoyi.system.service.IInvInventoryTransferDetailService;
import com.ruoyi.system.service.IInvInventoryTransferService;
import com.ruoyi.system.service.IWarehouseService;
import com.ruoyi.system.util.AbdulEmptyUtils;
import com.ruoyi.system.util.BaseResponse;
import com.ruoyi.system.util.StoreIdUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 库存调拨Controller
 *
 * @author ruoyi
 * @date 2023-07-18
 */
@RestController
@RequestMapping("/transfer/inventoryTransfer")
@Api(tags = "库存调拨管理")
public class InvInventoryTransferController extends BaseController {

    @Autowired
    private IInvInventoryTransferService invInventoryTransferService;

    @Autowired
    private IWarehouseService warehouseService;

    @Autowired
    private IInvInventoryTransferDetailService invInventoryTransferDetailService;

    @Autowired
    private StoreIdUtils storeIdUtils;

    /**
     * 查询库存调拨列表
     */
    @PostMapping("/page")
    @ApiOperation("查询库存调拨列表")
    public BaseResponse<Page<InvInventoryTransfer>> list(@RequestBody InvInventoryTransfer invInventoryTransfer) {
        LambdaQueryWrapper<InvInventoryTransfer> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(!AbdulEmptyUtils.isEmpty(invInventoryTransfer.getTransferOrderNo()), InvInventoryTransfer::getTransferOrderNo, invInventoryTransfer.getTransferOrderNo());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(invInventoryTransfer.getTransferTime()), InvInventoryTransfer::getTransferTime, invInventoryTransfer.getTransferTime());
        if (!AbdulEmptyUtils.isEmpty(invInventoryTransfer.getTransferTimeStart()) && !AbdulEmptyUtils.isEmpty(invInventoryTransfer.getTransferTimeEnd())) {
            wrapper.between(InvInventoryTransfer::getTransferTime, invInventoryTransfer.getTransferTimeStart(), invInventoryTransfer.getTransferTimeEnd());
        }
        wrapper.eq(!AbdulEmptyUtils.isEmpty(invInventoryTransfer.getTransferStaff()), InvInventoryTransfer::getTransferStaff, invInventoryTransfer.getTransferStaff());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(invInventoryTransfer.getInWarehouseType()), InvInventoryTransfer::getInWarehouseType, invInventoryTransfer.getInWarehouseType());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(invInventoryTransfer.getInWarehouse()), InvInventoryTransfer::getInWarehouse, invInventoryTransfer.getInWarehouse());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(invInventoryTransfer.getOutWarehouse()), InvInventoryTransfer::getOutWarehouse, invInventoryTransfer.getOutWarehouse());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(invInventoryTransfer.getTransferQuantity()), InvInventoryTransfer::getTransferQuantity, invInventoryTransfer.getTransferQuantity());
        if (!AbdulEmptyUtils.isEmpty(invInventoryTransfer.getCreateTimeStart()) && !AbdulEmptyUtils.isEmpty(invInventoryTransfer.getCreateTimeEnd())) {
            wrapper.between(InvInventoryTransfer::getCreateTime, invInventoryTransfer.getCreateTimeStart(), invInventoryTransfer.getCreateTimeEnd());
        }
        wrapper.eq(InvInventoryTransfer::getStoreId, storeIdUtils.getStoreId());
        wrapper.orderByDesc(InvInventoryTransfer::getUpdateTime);
        Page<InvInventoryTransfer> page = invInventoryTransferService.page(new Page<>(invInventoryTransfer.getPageNum(), invInventoryTransfer.getPageSize()), wrapper);
        if (!AbdulEmptyUtils.isEmpty(page.getRecords())) {
            Set<Long> warehouseIds = page.getRecords().stream()
                    .flatMap(record -> Stream.of(record.getInWarehouse(), record.getOutWarehouse()))
                    .collect(Collectors.toSet());//调出仓库id

            LambdaQueryWrapper<Warehouse> lqw = Wrappers.lambdaQuery();
            lqw.select(Warehouse::getId, Warehouse::getWarehouseName);
            lqw.in(Warehouse::getId, warehouseIds);
            lqw.eq(Warehouse::getStoreId, storeIdUtils.getStoreId());
            List<Warehouse> warehouseList = warehouseService.list(lqw);
            Map<Long, String> warehouseMap = warehouseList.stream().collect(Collectors.toMap(Warehouse::getId, Warehouse::getWarehouseName, (k1, k2) -> (String) k1));
            for (InvInventoryTransfer record : page.getRecords()) {
                Long inWarehouse = record.getInWarehouse();
                if (!AbdulEmptyUtils.isEmpty(warehouseMap)) {
                    record.setInWarehouseDesc(warehouseMap.get(inWarehouse));
                }
                Long outWarehouse = record.getOutWarehouse();
                if (!AbdulEmptyUtils.isEmpty(warehouseMap)) {
                    record.setOutWarehouseDesc(warehouseMap.get(outWarehouse));
                }
            }
        }
        return BaseResponse.success(page);
    }

    /**
     * 获取库存调拨详细信息
     */
    @GetMapping(value = "/{id}")
    @ApiOperation("获取库存调拨详细信息")
    public BaseResponse<InvInventoryTransfer> getInfo(@PathVariable("id") Long id) {

        InvInventoryTransfer transfer = invInventoryTransferService.getById(id);
        if (AbdulEmptyUtils.isEmpty(transfer)) {
            return BaseResponse.error("数据不存在");
        }
        LambdaQueryWrapper<Warehouse> lqw = Wrappers.lambdaQuery();
        lqw.select(Warehouse::getId, Warehouse::getWarehouseName);
        lqw.in(Warehouse::getId, transfer.getInWarehouse(), transfer.getOutWarehouse());
        lqw.eq(Warehouse::getStoreId, storeIdUtils.getStoreId());
        List<Warehouse> warehouseList = warehouseService.list(lqw);
        Map<Long, String> warehouseMap = warehouseList.stream().collect(Collectors.toMap(Warehouse::getId, Warehouse::getWarehouseName, (k1, k2) -> (String) k1));
        if (!AbdulEmptyUtils.isEmpty(warehouseMap)){
            transfer.setInWarehouseDesc(warehouseMap.get(transfer.getInWarehouse()));
            transfer.setOutWarehouseDesc(warehouseMap.get(transfer.getOutWarehouse()));
        }
        LambdaQueryWrapper<InvInventoryTransferDetail> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(InvInventoryTransferDetail::getTransferId, id);
        wrapper.eq(InvInventoryTransferDetail::getStoreId, storeIdUtils.getStoreId());
        wrapper.eq(InvInventoryTransferDetail::getDetailType, 1);
        List<InvInventoryTransferDetail> list = invInventoryTransferDetailService.list(wrapper);
        if (!AbdulEmptyUtils.isEmpty(list)) {
            transfer.setInvInventoryTransferDetailList(list);
        }
        return BaseResponse.success(transfer);
    }

    /**
     * 新增库存调拨
     */
    @PostMapping("/save")
    @ApiOperation("新增库存调拨")
    public BaseResponse<Boolean> add(@RequestBody InvInventoryTransfer invInventoryTransfer) {
        return BaseResponse.success(invInventoryTransferService.add(invInventoryTransfer));
    }

    /**
     * 修改库存调拨
     */
    @PutMapping("/update")
    @ApiOperation("修改库存调拨")
    public BaseResponse<Boolean> edit(@RequestBody InvInventoryTransfer invInventoryTransfer) {
        return BaseResponse.success(invInventoryTransferService.edit(invInventoryTransfer));
    }

    /**
     * 删除库存调拨
     */
    @DeleteMapping("/{ids}")
    @ApiOperation("删除库存调拨")
    public BaseResponse<Boolean> remove(@PathVariable Long[] ids) {
        LambdaQueryWrapper<InvInventoryTransfer> wrapper = Wrappers.lambdaQuery();
        wrapper.in(InvInventoryTransfer::getId, Arrays.asList(ids));
        wrapper.eq(InvInventoryTransfer::getStoreId, storeIdUtils.getStoreId());
        List<InvInventoryTransfer> list = invInventoryTransferService.list();
        if (AbdulEmptyUtils.isEmpty(list)) {
            return BaseResponse.error("数据不存在");
        }
        Set<Long> idList = list.stream().map(InvInventoryTransfer::getId).collect(Collectors.toSet());
        invInventoryTransferService.removeByIds(idList);
        LambdaQueryWrapper<InvInventoryTransferDetail> lqw = Wrappers.lambdaQuery();
        lqw.in(InvInventoryTransferDetail::getTransferId, idList);
        lqw.eq(InvInventoryTransferDetail::getDetailType,1);
        return BaseResponse.success(invInventoryTransferDetailService.remove(lqw));
    }

    /**
     * 导出库存调拨列表
     */
//    @PostMapping("/export")
//    @ApiOperation("导出库存调拨列表")
//    public void export(HttpServletResponse response, InvInventoryTransfer invInventoryTransfer) {
//        QueryWrapper<InvInventoryTransfer> queryWrapper = new QueryWrapper<>(invInventoryTransfer);
//        List<InvInventoryTransfer> list = invInventoryTransferService.list(queryWrapper);
//        ExcelUtil<InvInventoryTransfer> util = new ExcelUtil<>(InvInventoryTransfer.class);
//        util.exportExcel(response, list, "库存调拨数据");
//    }

    /**
     * 审核
     */
    @GetMapping("/audit")
    @ApiOperation("审核")
    public BaseResponse<Boolean> audit(Long id) {
        Boolean result = invInventoryTransferService.audit(id);
        return BaseResponse.success(result);
    }
}
